#!/usr/bin/env python
# -*- coding: utf-8 -*-


from time import sleep
from flask_socketio import SocketIO
from threading import Thread


class MockProxyClient:
    def __init__(self, socketio: SocketIO):
        self.socketio = socketio
        self.device_list = [
            {
                "name": "mock_device_1",
                "sn": "1111111111",
                "type": "OpenHarmony-5.0.2",
                "ip": ["127.0.0.1", "172.16.1.84"],
                "proxy": "172.16.1.84",
                "status": "online",
            },
            {
                "name": "mock_device_2",
                "sn": "2222222222",
                "type": "KaihongOS-4.1.0",
                "ip": ["127.0.0.1", "172.16.3.224"],
                "proxy": "172.16.3.224",
                "status": "online",
            }
        ]
        self.device_list_backup = [
            {
                "name": "mock_device_3",
                "sn": "3333333333",
                "type": "OpenHarmony-5.0.2",
                "ip": ["127.0.0.1", "172.16.1.84"],
                "proxy": "172.16.1.84",
                "status": "online",
            }
        ]
        self.switch_device_list = False
        self.stop_refresh = False
        self.refresh_thread = Thread(target=self.refresh_device_list)
        self.refresh_thread.start()

    def close_all(self):
        self.stop_refresh = True
        self.refresh_thread.join()
    
    def __del__(self):
        self.close_all()

    def send_request(self, reqquest_data):
        api = reqquest_data['api']
        if api == 'get_device_list':
            if self.switch_device_list:
                return {"retval": 0 , "result": {"devices": self.device_list_backup}}
            else:
                return {"retval": 0 , "result": {"devices": self.device_list}}
        return {"retval": 1, "message": f"devcie api: {api} not supported in mock mode"}

    def get_device(self, device_sn):
        pass

    def refresh_device_list(self):
        # wait for app initialization
        sleep(15)
        while not self.stop_refresh:
            if self.switch_device_list:
                self.socketio.emit('refresh_device_list', self.device_list_backup)
                self.switch_device_list = False
            else:
                self.socketio.emit('refresh_device_list', self.device_list)
                self.switch_device_list = True
            sleep(5)